package com.yiwei.ydd.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.yiwei.ydd.Application;
import com.yiwei.ydd.R;
import com.yiwei.ydd.api.Api;
import com.yiwei.ydd.api.model.SettingCustomerModel;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.util.Dialog;
import com.yiwei.ydd.util.Network;
import com.yiwei.ydd.util.PreferenceUtils;
import com.yiwei.ydd.util.RxLifeUtil;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.util.Util;
import com.yiwei.ydd.view.V19FrameLayout;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class ChatCenterActivity extends BaseActivity {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.txt_phone)
    TextView txtPhone;
    @BindView(R.id.txt_wechat)
    TextView txtWechat;
    @BindView(R.id.txt_wechat_comment)
    TextView txtWechatComment;
    @BindView(R.id.txt_qq)
    TextView txtQq;
    @BindView(R.id.txt_email)
    TextView txtEmail;
    @BindView(R.id.txt_time)
    TextView txtTime;
    @BindView(R.id.img_code_one)
    ImageView imgCodeOne;
    @BindView(R.id.img_code_two)
    ImageView imgCodeTwo;
    @BindView(R.id.btn_call)
    TextView btnCall;

    private Unbinder unbiner;
    private SettingCustomerModel.DatasBean totalData;
    private String code_one;
    private String code_two;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_chat_center);
        initBar();
        unbiner = ButterKnife.bind(this);
        init();
    }

    private void init() {
        txtTitle.setText("客服中心");
        txtRight.setVisibility(View.VISIBLE);
        txtRight.setText("意见反馈");
        getSettingCustomer();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbiner.unbind();
        unbiner = null;
    }

    public void getSettingCustomer() {
        if (!Network.checkNetwork(this)) {
            ToastUtil.show(this, "网络连接失败");
            return;
        }

        loadingDialog.show();
        Api.api_service.getSettingCustomer().compose(RxLifeUtil.checkOn(this)).
                doFinally(() -> {
                    try {
                        loadingDialog.dismiss();
                    } catch (NullPointerException e) {

                    }
                }).
                subscribe(result -> {
                    setData(result.datas);
                });
    }

    public static void saveImageToGallery(Context context, Bitmap bmp) {
        // 首先保存图片
        File appDir = new File(Environment.getExternalStorageDirectory(), "ydd");
        if (!appDir.exists()) {
            appDir.mkdir();
        }
        String fileName = System.currentTimeMillis() + ".jpg";
        File file = new File(appDir, fileName);
        try {
            FileOutputStream fos = new FileOutputStream(file);
            bmp.compress(Bitmap.CompressFormat.JPEG, 100, fos);
            fos.flush();
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 其次把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(context.getContentResolver(),
                    file.getAbsolutePath(), fileName, null);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // 最后通知图库更新
        context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + file.getAbsolutePath())));
        ToastUtil.makeText(context, "保存成功").show();
    }

    private void setData(SettingCustomerModel.DatasBean datas) {
        totalData = datas;
        txtQq.setText(datas.qq);
        txtEmail.setText(datas.email);
        txtPhone.setText(datas.telphone);
        txtWechat.setText(datas.kf_wechat_no);
        txtWechatComment.setText(datas.gf_wechat_no);
        Glide.with(this).load(datas.kf_qrcode_link).asBitmap().into(imgCodeTwo);
        imgCodeTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Dialog.showBigIcon(ChatCenterActivity.this, datas.kf_qrcode_link);
            }
        });
        Glide.with(this).load(datas.gf_qrcode_link).asBitmap().into(imgCodeOne);
        imgCodeOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Dialog.showBigIcon(ChatCenterActivity.this, datas.gf_qrcode_link);
            }
        });
        StringBuilder builder = new StringBuilder();
        SettingCustomerModel.DatasBean.TimeBean item = datas.time;
        builder.append(item.day).append(" 上午").append(item.am).append("\n").append("下午").append(item.pm);
        txtTime.setText(builder);

    }

    @OnClick({R.id.btn_save_code_two, R.id.btn_save_code_one, R.id.btn_back, R.id.txt_right, R.id.btn_call})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_save_code_one:
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        saveImageToGallery(ChatCenterActivity.this, ((BitmapDrawable) imgCodeOne.getDrawable()).getBitmap());
                    }

                }, R.string.camera_storage_card_p, R.string.ask_again, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.btn_save_code_two:
                checkPermission(new CheckPermListener() {
                    @Override
                    public void superPermission() {
                        saveImageToGallery(ChatCenterActivity.this, ((BitmapDrawable) imgCodeTwo.getDrawable()).getBitmap());
                    }

                }, R.string.camera_storage_card_p, R.string.ask_again, Manifest.permission.WRITE_EXTERNAL_STORAGE);
                break;
            case R.id.btn_back:
                finish();
                break;
            case R.id.txt_right:
                if (Util.getIsLogin(this))
                Util.startActivity(this, MySuggestActivity.class);
                break;
            case R.id.btn_call:
                if (totalData == null) {
                    return;
                }
                Dialog.showDefaultDialog(this, "提示", "拨打客服电话" + totalData.telphone, "拨打", "取消", false, new Dialog.DialogDefaultClickListener() {
                    @Override
                    public void confirm() {

                    }

                    @Override
                    public void cancel() {
                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + totalData.telphone));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                    }
                });
                break;
        }
    }

}
